package com.nantai.jiafang.nantaijiafang.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.nantai.jiafang.nantaijiafang.Luban2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.OnCompressListener;

import static android.content.ContentValues.TAG;

/**
 * Created by wuning on 2016/8/4.
 */
public class Tools {


    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static boolean isNetAvailuable(Context context) {
// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
        for (int i = 0; i < networkInfo.length; i++) {
            if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
        return false;
    }

    public static String getSharedValue(Context context, String fileName, String name) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,
                Activity.MODE_PRIVATE);
        return sharedPreferences.getString(name, "");
    }

    public static void setSharedValue(Context context, String fileName, String name, String value) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(name, value);
        editor.commit();
    }

    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
                System.out.println("文件已删除");
            }
        }else{
            System.out.println("文件路径不存在");
        }
    }

    /**
     * 鲁班（改进版）调用，用于单个和多个图片压缩
     * @param context           上下文也可以忽略
     * @param pathList          需要压缩的图片集，单张图片自己修改
     * @param compressImage     接口，用于其他地方需要用到压缩文件时回调
     */
    public static void compressMore(Context context,final List<String> pathList,CompressImage compressImage){
        Toast.makeText(context, "压缩中", Toast.LENGTH_SHORT).show();
        ArrayList<File> files=new ArrayList<>();
        for (String path :
                pathList) {
            files.add(new File(path));
        }
                Luban2.get(context)
                        .load(files)                     //传人要压缩的图片集，也可以是单张图片如 .load(new File(path))
                        .putGear(Luban2.THIRD_GEAR)      //设定压缩档次，默认三挡
                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                               // AppManager.I().currentActivity().showDialog("加载中...");
                            }
                            @Override
                            public void onSuccess(File file) {
                                //每压缩完成一张就会有回调文件，多文件压缩onSuccess会不停地被调用返回数据，然后在下列代码中回调出去
                                    compressImage.success(file.getPath());
                                }

                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();    //启动压缩
    }

    /**
     * 文件复制
     * @param oldPath  要复制的文件路径
     * @param newPath  复制后新的文件路径
     */
    public   void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            Log.e(TAG, "copyFile: 复制单个文件操作出错");

            e.printStackTrace();

        }

    }



}
